package com.ruoyi.channel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.channel.domain.ChannelMsgSent;
import com.ruoyi.channel.domain.TChannelPushDis;
import com.ruoyi.channel.domain.bo.PushOperate;
import com.ruoyi.channel.domain.bo.TChannelPushDisBo;
import com.ruoyi.channel.domain.vo.ChannelCustomerInfoVo;
import com.ruoyi.channel.domain.vo.ChannelPushDisVo;
import com.ruoyi.channel.domain.vo.TChannelPushDisVo;
import com.ruoyi.channel.mapper.TChannelDataConfMapper;
import com.ruoyi.channel.mapper.TChannelPushDisMapper;
import com.ruoyi.channel.service.ChannelDisService;
import com.ruoyi.channel.service.ITChannelPushDisService;
import com.ruoyi.channelApi.domain.CfCrmRequest;
import com.ruoyi.channelApi.domain.ChannelRequest;
import com.ruoyi.channelApi.domain.vo.TChannelPushVo;
import com.ruoyi.channelApi.mapper.TChannelPushMapper;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.domain.Customer;
import com.ruoyi.customer.domain.CustomerChange;
import com.ruoyi.customer.domain.Remark;
import com.ruoyi.customer.domain.TotalComster;
import com.ruoyi.customer.domain.vo.CustomerVo;
import com.ruoyi.customer.mapper.CustomerMapper;
import com.ruoyi.customer.mapper.RemarkMapper;
import com.ruoyi.customer.mapper.TotalComsterMapper;
import com.ruoyi.customer.service.CommonService;
import com.ruoyi.disCustomer.domain.TCustomerDisRecord;
import com.ruoyi.disCustomer.mapper.TCustomerDisRecordMapper;
import com.ruoyi.enums.BusTypeEnum;
import com.ruoyi.enums.ChannelPushEnum;
import com.ruoyi.enums.CompanyStatusEnum;
import com.ruoyi.system.mapper.SysUserMapper;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 渠道数据分配Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-02
 */
@RequiredArgsConstructor
@Service
public class TChannelPushDisServiceImpl implements ITChannelPushDisService {

    private final TChannelPushDisMapper baseMapper;
    private final CustomerMapper customerMapper;
    private final SysUserMapper userMapper;
    private final RemarkMapper remarkMapper;
    private final TChannelPushMapper channelPushMapper;
    private final TChannelDataConfMapper channelDataConfMapper;

    private final TCustomerDisRecordMapper disRecordMapper;
    private final ChannelDisService channelDisService;
    private final TotalComsterMapper totalComsterMapper;

    private final CommonService commonService;

    /**
     * 查询渠道数据分配
     */
    @Override
    public TChannelPushDisVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public TableDataInfo<ChannelPushDisVo> queryPageDisList(TChannelPushDisBo bo, PageQuery pageQuery) {
        Page<ChannelPushDisVo> result = null;
        if (Objects.equals("1", bo.getPageType())) {
            result = baseMapper.selectPageChannelPushVoList(pageQuery.build(),
                    this.queryWrapper(bo));
        } else if (Objects.equals("2", bo.getPageType())) {
            result = baseMapper.selectMangePageChannelPushVoList(pageQuery.build(),
                    this.queryWrapper(bo));
        }
        result.getRecords().forEach(it -> {
            String operateResult = it.getOperateResult();
            if (StringUtils.isNotBlank(operateResult)) {
                Map map = JsonUtils.parseObject(operateResult, Map.class);
                if (map != null && !map.isEmpty()) {
                    String operator = String.valueOf(map.get("operator"));
                    String operatorTime = String.valueOf(map.get("operatorTime"));
                    String operatorReason = String.valueOf(map.get("operatorReason"));
                    if (StringUtils.isNotBlank(operator) && StringUtils.isNotBlank(operatorReason)
                            && StringUtils.isNotBlank(operatorTime)) {
                        it.setOperateResult(operator + "---" + operatorTime + "[" + operatorReason + "]");
                    }
                }
            }
        });
        return TableDataInfo.build(result);
    }


    /**
     * 查询渠道数据分配列表
     */
    @Override
    public TableDataInfo<TChannelPushDisVo> queryPageList(TChannelPushDisBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TChannelPushDis> lqw = buildQueryWrapper(bo);
        Page<TChannelPushDisVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询渠道数据分配列表
     */
    @Override
    public List<TChannelPushDisVo> queryList(TChannelPushDisBo bo) {
        LambdaQueryWrapper<TChannelPushDis> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private Wrapper<TChannelPushDisBo> queryWrapper(TChannelPushDisBo bo) {
        QueryWrapper<TChannelPushDisBo> query = Wrappers.query();
        Map<String, Object> params = bo.getParams();
        // 渠道来源
        query.eq(StringUtils.isNotBlank(bo.getTel()), "a.tel", bo.getTel());
        query.eq(StringUtils.isNotBlank(bo.getChannelSource()), "pd.channel_source", bo.getChannelSource());
        query.between(params.get("beginTime") != null && params.get("endTime") != null,
                "a.push_time", params.get("beginTime"), params.get("endTime"));
        query.eq(StringUtils.isNotBlank(bo.getTel()), "a.tel", bo.getTel());
        query.eq(StringUtils.isNotBlank(bo.getOperateFlag()), "pd.operate_flag", bo.getOperateFlag());
        if (Objects.equals("2", bo.getPageType())) {
            query.apply(" pd.operate_flag = 1 and chs.user_id = " + LoginHelper.getUserId());
        }
        query.orderByDesc("a.push_time");
        return query;
    }

    private LambdaQueryWrapper<TChannelPushDis> buildQueryWrapper(TChannelPushDisBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TChannelPushDis> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getChannelPushId() != null, TChannelPushDis::getChannelPushId, bo.getChannelPushId());
        lqw.eq(StringUtils.isNotBlank(bo.getTel()), TChannelPushDis::getTel, bo.getTel());
        lqw.eq(bo.getUserId() != null, TChannelPushDis::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getDataInfo()), TChannelPushDis::getDataInfo, bo.getDataInfo());
        lqw.eq(bo.getCreateId() != null, TChannelPushDis::getCreateId, bo.getCreateId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TChannelPushDis::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增渠道数据分配
     */
    @Override
    public Boolean insertByBo(TChannelPushDisBo bo) {
        TChannelPushDis add = BeanUtil.toBean(bo, TChannelPushDis.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改渠道数据分配
     */
    @Override
    public Boolean updateByBo(TChannelPushDisBo bo) {
        TChannelPushDis update = BeanUtil.toBean(bo, TChannelPushDis.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TChannelPushDis entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除渠道数据分配
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushOperate(PushOperate pushOperate) {
        String type = pushOperate.getType();
        Long id = pushOperate.getId();
        Long channelPushId = pushOperate.getChannelPushId();
        String channelName = pushOperate.getChannelName();
        String reason = pushOperate.getReason();
        // 客户Id
        Long customerId = pushOperate.getCustomerId();
        // 放弃
        TChannelPushDis tChannelPushDis = new TChannelPushDis();
        tChannelPushDis.setOperateFlag(type);
        // 分配一下
        if (Objects.equals("2", type)) {
            // 获取渠道信息
            TChannelPushVo tChannelPushVo = Optional.ofNullable(channelPushMapper.selectVoById(channelPushId))
                    .orElseThrow(() -> new ServiceException("推送信息不存在"));
            String dataInfo = tChannelPushVo.getDataInfo();
            if (!StringUtils.isNotBlank(dataInfo)) {
                throw new ServiceException("推送的客户信息不存在");
            }
            //String remarks = "";
            String name = "";
            //String ed = "";
            if (Objects.equals(tChannelPushVo.getChannelSource(), ChannelPushEnum.CRM_CHANNEL.getValue())) {
                ChannelRequest channelRequest = JsonUtils.parseObject(tChannelPushVo.getDataInfo(),
                        ChannelRequest.class);
                if (channelRequest != null) {
                    name = channelRequest.getCname();
                    //        remarks = channelRequest.getRemarks();
                    //        ed = channelRequest.getEd();

                    //        String time = channelRequest.getSubtime();
                    //
                    //        StringBuilder stringBuilder = new StringBuilder();
                    //        if (StringUtils.isNotBlank(remarks)) {
                    //            stringBuilder.append(remarks);
                    //        }
                    //        if (StringUtils.isNotBlank(ed)) {
                    //            stringBuilder.append(" 额度：").append(ed).append(" ");
                    //            ;
                    //        }
                    //        if (StringUtils.isNotBlank(time)) {
                    //            stringBuilder.append(" 时间：").append(time).append(" ");
                    //        }
                    //        remarks = stringBuilder.toString();
                }
            } else if (Objects.equals(tChannelPushVo.getChannelSource(), ChannelPushEnum.CF_CRM_CHANNEL.getValue())) {
                CfCrmRequest crmRequest = JsonUtils.parseObject(tChannelPushVo.getDataInfo(), CfCrmRequest.class);
                if (crmRequest != null) {
                    name = crmRequest.getName();
                    //remarks = crmRequest.getRemark();
                    //ed = crmRequest.getLoanAmount();
                    //String time = crmRequest.getReceivetime();
                    //StringBuilder stringBuilder = new StringBuilder();
                    //if (StringUtils.isNotBlank(remarks)) {
                    //    stringBuilder.append(remarks);
                    //}
                    //if (StringUtils.isNotBlank(ed)) {
                    //    stringBuilder.append(" 额度：").append(ed).append(" ");
                    //}
                    //if (StringUtils.isNotBlank(time)) {
                    //    stringBuilder.append(" 时间：").append(time).append(" ");
                    //}
                    //remarks = stringBuilder.toString();
                }
            }
            tChannelPushDis.setOperateFlag("0");
            // 获取渠道备注信息
            CustomerVo customerVo = Optional.ofNullable(customerMapper.selectVoById(customerId))
                    .orElseThrow(() -> new ServiceException("客户信息不存在"));

            String channelIdsByTel = channelDataConfMapper.getChannelIdsByTel(pushOperate.getTel());
            Long totalCustomerId = customerVo.getTotalCustomerId();
            // 更新总库信息
            TotalComster totalComster = new TotalComster();
            totalComster.setId(totalCustomerId);
            totalComster.setChannelIds(channelIdsByTel);
            totalComsterMapper.updateById(totalComster);

            Customer customer = new Customer();
            customer.setId(customerId);
            customer.setTaskId(pushOperate.getUserId());
            // 保存备注信息
            //if (StringUtils.isNotBlank(remarks)) {
            //    // 新增一条备注记录信息
            //    Remark remark = new Remark();
            //    remark.setContent(remarks);
            //    remark.setCustomerId(customerId);
            //    remark.setCreateBy(channelName);
            //    remark.setUserId(LoginHelper.getUserId());
            //    remarkMapper.insert(remark);
            //    StringBuilder stringBuilder = new StringBuilder();
            //    String remarkInfo =
            //            remarks + "--" + channelName + "[" + DateUtils.parseDateToStr(
            //                    DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()) + "]";
            //    stringBuilder.append(remarkInfo);
            //    stringBuilder.append("<br/>");
            //    stringBuilder.append(customerVo.getBz());
            //    customer.setBz(stringBuilder.toString());
            //}
            customer.setName(name + "-" + customerVo.getName());
            customer.setLastRemarkTime(DateUtils.getNowDate());
            customer.setCompanyStatus(CompanyStatusEnum.DRL.getCode());

            customer.setChannelIds(channelIdsByTel);

            // 保存下推记录
            TCustomerDisRecord disRecord = new TCustomerDisRecord();
            disRecord.setBusType(BusTypeEnum.CHANNEL_PUSH.getCode());
            disRecord.setCustomerId(customerId);
            disRecord.setOperateDisId(-1L);
            disRecord.setOperateDeptId(-1L);
            disRecord.setOperateDisName(channelName);
            Optional.ofNullable(userMapper.selectUserById(pushOperate.getUserId())).ifPresent(it -> {
                customer.setDistributeDeptId(it.getDeptId());
                disRecord.setDisDeptId(it.getDeptId());
                disRecord.setDisName(it.getNickName());
            });
            disRecord.setDisUserId(pushOperate.getUserId());
            disRecord.setTaskId(pushOperate.getUserId());
            disRecord.setCustomerName(name);
            disRecord.setOperateDisName(channelName);
            disRecord.setCreateTime(DateUtils.getNowDate());
            disRecordMapper.insert(disRecord);

            customerMapper.updateById(customer);

            // 记录客户名称变更
            String newOldJson = JsonUtils.toJsonString(customer);
            String oldOldJson = JsonUtils.toJsonString(customerVo);
            CustomerChange newCustomerChange = BeanUtil.toBean(customer, CustomerChange.class);
            CustomerChange oldCustomerChange = BeanUtil.toBean(customerVo, CustomerChange.class);
            Map<String, Object> mapChangeInfo = new HashMap<>();
            mapChangeInfo.put("customerId", customerId);
            mapChangeInfo.put("tel", customerVo.getTel());
            mapChangeInfo.put("createId", 14L);
            mapChangeInfo.put("createBy", channelName);
            mapChangeInfo.put("type", "customerInfoChange");
            commonService.customerChangeRecord(oldCustomerChange, oldOldJson, newCustomerChange, newOldJson,
                    mapChangeInfo, "1");

            // 发送消息
            ChannelMsgSent channelMsgSent = new ChannelMsgSent();
            channelMsgSent.setId(pushOperate.getUserId());
            channelMsgSent.setChannelName(channelName);
            channelMsgSent.setTel(pushOperate.getTel());
            channelDisService.sentToBusMsg(channelMsgSent);


        }
        tChannelPushDis.setId(id);
        Map<String, String> map = new HashMap<>();
        map.put("operator", LoginHelper.getLoginUser().getNickName());
        map.put("operatorUserId", String.valueOf(LoginHelper.getUserId()));
        map.put("operatorReason", reason);
        map.put("operatorTime", DateUtils.getTime());
        tChannelPushDis.setOperateResult(JsonUtils.toJsonString(map));
        baseMapper.updateById(tChannelPushDis);
    }

    @Override
    public List<ChannelCustomerInfoVo> getChannelCustomerList(PushOperate pushOperate) {
        CustomerVo customerVo = Optional.ofNullable(customerMapper.selectVoById(pushOperate.getId()))
                .orElseThrow(() -> new ServiceException("客户信息没有找到"));
        String tel = customerVo.getTel();
        return baseMapper.channelPushTelInfo(tel);
    }

}
